<?php
include '../includes/cPlayer.php';
include '../includes/cDatabase.php';
include '../includes/variables.php';
include '../includes/cPage.php';
include '../includes/cDates.php';

$cPage = new page("Add Scores From File");
echo $cPage->getTitle();
echo $cPage->pageStringStart();
echo $cPage->contentStringStart();

if (@$_GET['form'] == "yes")
{
	// Check user and password
	if ($_POST['fileName'] && $_POST['selectWeek'] && $_POST['selectPosition'])
	{
		echo "<BR>fileName:".$_POST['fileName'];
		echo "<BR>selectWeek:".$_POST['selectWeek'];
		echo "<BR>selectPosition:".$_POST['selectPosition'];
		searchFileForString2010($_POST['fileName'], $_POST['selectWeek']);
	}
	else
	{
		echo "ERROR: Parameters Missing";
	}
	?>
	<div align="center">
	<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=yes" method="POST">
	  <table width='400' border='0'>
		<tr>
		  <td colspan="2" align="center">
			  <INPUT TYPE="BUTTON" VALUE="Main Menu" ONCLICK="window.location.href='http://localhost'"></td>
	 	</tr>
	  </table>
	</form>
	</div>
	
	<?php
}
else
{
$cDatabase = new database();

$connect = $cDatabase->connectToDatabase();
$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
$db = $cDatabase->selectDatabase($connect, $activeDatabase);

$selectArray[0] = '*';
$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, NULL, NULL, NULL, NULL);
	
// Get the number of weeks from the DB
$finfo = mysqli_fetch_fields($result);
$numberWeeks = 0;
for ($i = 0; $i < mysqli_num_fields($result); $i++)
{
	if ( ( substr(trim($finfo[$i]->name), 0 , 4) == 'week'))
		$numberWeeks++;
}
?>
<div align="center">
<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=yes" method="POST">
  <table width='400' border='0'>
    <tr>
      <td><div align="center">Filename</div></td>
    </tr>
    <tr>
      <td><div align="center">
		<select name="selectWeek">
			<?php
				for ($j = 1; $j <= $numberWeeks; $j++)
				{
	    		  	echo"<option value = '" .$j. "'>" .$j. "</option>";
				}
			?>
		</select>
	    <select name="selectPosition">
			<option value = 'GK'>GK</option>
			<option value = 'DEF'>DEF</option>
			<option value = 'MID'>MID</option>
			<option value = 'ATT'>ATT</option>
		</select>
        <input type='text' name='fileName' size='20' maxlength='30' value=<?php echo @$_POST['fileName'] ?>>
      </div></td>
    </tr>
	<tr>
	  <td colspan="2" align="center">
	    <p>&nbsp;</p>
	    <p><input name="loginButton" type="submit" id="login" value="CREATE">
        </p></td>
 	</tr>
  </table>
</form>
</div>

<?php
}
function AddPlayerToDB($code, $name, $team, $value, $position, $score)
{
	$error = 0;
	$cPlayer = new player($code);
	
	$error |= $cPlayer->addPlayerName($name);
	$error |= $cPlayer->addPlayerTeam($team);
	$error |= $cPlayer->addPlayerValue($value);
	$error |= $cPlayer->addPlayerPosition($position);
	$error |= $cPlayer->addPlayerLastYearScore($score);
	
	if (!$error)
	{
		$cDatabase = new database();

		$connect = $cDatabase->connectToDatabase();
		$activeDatabase = $cDatabase->getActiveDatabase($connect);
	
		$db = $cDatabase->selectDatabase($connect, $activeDatabase);
		
		// Check code does not already exist in DB
		$selectArray[0] = '*';
		$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, "playerCode", $cPlayer->getPlayerCode(), NULL, NULL);
		if ($result)
		{
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			if ($code == $row['playerCode'])
			{
				// We already found the player in the database.
				echo "<BR>ERROR: Code ".$cPlayer->getPlayerCode()." already exists: ";
				echo $row['playerCode']." ".$row['playerName']." ".$row['playerTeam']." £".$row['playerValue']."m ".$row['playerPosition'];
				
				// Check to see if this player has changed teams.
				if ($row['playerTeam'] != $cPlayer->getPlayerTeam())
				{
					echo "<BR>ERROR: Code ".$cPlayer->getPlayerCode()." has changed teams from ".$row['playerTeam']." to ".$cPlayer->getPlayerTeam();
					$cDatabase->updatePlayer ($connect, 'playerTeam', $cPlayer->getPlayerTeam(), $cPlayer->getPlayerCode());
				}
			}
			else
			{
				// Add a row to the table
				$cDatabase->insertPlayer($connect, $cPlayer->getPlayerCode(), $cPlayer->getPlayerName(),
					$cPlayer->getPlayerTeam(), $cPlayer->getPlayerValue(), $cPlayer->getPlayerPosition(), $cPlayer->getPlayerLastYearScore() );
			}
		}
		else
		{
			echo "<BR>ERROR:DB Error";
		}
	}
	else
	{
		echo "<BR>ERROR: Player has not been added";
	}
}

function searchFileForString($file,$week) 
{
	$section = file_get_contents($file, true);
	if ($section != FALSE)
	{	
		// e,g, 2009
		// <td><a href='/statistics/points/1001'>van der Sar, E</a></td>
		//<td><a href='/statistics/club-by-club/MUN'>Manchester United</a></td>
		//<td>&pound;4m</td>
		//<td>0.0</td>
		//<td>0</td>
		
		// e.g. 2012
		//<td class='first'><a href='http://fantasyfootball.telegraph.co.uk/statistics/points/2027'>Bosingwa, J</a></td>
		//<td class='second'><a href='http://fantasyfootball.telegraph.co.uk/statistics/teams/CHE'>Chelsea</a></td>
		//<td class='third'>&pound;3.8 m</td>
		//<td class='fourth'>1.6</td>
		//<td class='fifth last'>6</td>
		
		$PlayerIdPattern = "/\/statistics\/points\//";
		$PlayerIdFixedOffset = strlen($PlayerIdPattern) - 5;
		
		$PlayerRowDetect = "/<td class='fifth last'>/";
		$PlayerRowDetectOffset = 23;
		
		//<td class='first'><a href='/statistics/points/1001'>van der Sar, E</a></td>
		//<td class='second'><a href='/statistics/club-by-club/MUN'>Manchester United</a></td>
		//<td class='third'>&pound;4.0 m</td>
		//<td class='fourth'>0.0</td>
		//<td class='fifth last'>0</td>
		
		//$PlayerIdPattern = "/a href='\/statistics\/points\//";
		//$PlayerIdFixedOffset = strlen($PlayerIdPattern) - 5;
		
		// e.g. 2010 <tr id='p1002'><td>Cech, P</td><td>CHE</td><td>4.0</td><td>10.4%</td><td>6</td><td></td></tr>
		//$PlayerIdPattern = "/<tr id='p/";
		//$PlayerIdFixedOffset = strlen($PlayerIdPattern) - 2;
		
		//$PlayerRowDetect = "/<td>/";
		//$PlayerRowDetectOffset = 4;
		
		//$PlayerRowDetect = "/<td class/";
		//$PlayerRowDetectOffset = 23;
		
		
		$PlayerLastPointsStartFixedOffset = strlen($PlayerLastPointsStartPattern) - 1;
		
		$offset = 0;
		
		while(preg_match($PlayerIdPattern, $section, $matches, PREG_OFFSET_CAPTURE, $offset))
		{
			$PlayerIdOffset = $matches[0][1] + $PlayerIdFixedOffset;		// Index into $section string to where the player code ID starts
	
			echo"<BR>Code ".$section[$PlayerIdOffset].$section[$PlayerIdOffset+1].$section[$PlayerIdOffset+2].$section[$PlayerIdOffset+3];
			$PlayerCodeArray = array($section[$PlayerIdOffset],$section[$PlayerIdOffset+1],$section[$PlayerIdOffset+2],$section[$PlayerIdOffset+3]);
			
			$PlayerCode = implode($PlayerCodeArray);
			
			$offset = $PlayerIdOffset;
			
			// Count four lots of <td>
			//for ($count = 0; $count <= 4; $count++)
			{
				if (preg_match($PlayerRowDetect, $section, $matches, PREG_OFFSET_CAPTURE, $offset))
				{
					
					$offset = $matches[0][1]+$PlayerRowDetectOffset;
					echo "score".$section[$offset]."----".$section[$offset+1];
					//if ($count == 4)
					{
						// Get start offset for points
						$totalScoreStartOffset = $matches[0][1]+$PlayerRowDetectOffset;
						
						// get end offset for points
						if (preg_match("/<\/td>/", $section, $matches, PREG_OFFSET_CAPTURE, $offset))
						{
							$totalScoreEndOffset = $matches[0][1];
						}
						for ($scoreCount = 0; $scoreCount < ($totalScoreEndOffset-$totalScoreStartOffset); $scoreCount++)
						{
							$ScoreArray[$scoreCount] = $section[$totalScoreStartOffset+$scoreCount];
						}
						
						if ($totalScoreEndOffset != $totalScoreStartOffset)
						{
							$totalScore = implode($ScoreArray);
						}
						else
						{
							$totalScore = 0;
						}
						unset($ScoreArray);
					}
				}
			}
			// Get current total score for this player
			$cDatabase = new database();

			$connect = $cDatabase->connectToDatabase();
			$activeDatabase = $cDatabase->getActiveDatabase($connect);
			$db = $cDatabase->selectDatabase($connect, $activeDatabase);
			
			$maxWeeks = $cDatabase->GetMaxWeeks($connect);
			
			$selectArray[0] = '*';
			$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, 'playerCode', $PlayerCode, NULL, NULL);
			//echo "<BR>result $result ".$row['playerName'];
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			if ($row['playerName'] == NULL)
			{
				// This player is not in the database
				echo "<BR>Player not in database ".$PlayerCode;
			}
			
			$currentPlayerScore = getPlayerScore($row, $maxWeeks);
			
			$thisWeekScore = $totalScore - $currentPlayerScore;
			
			echo "<BR>playerScore = ".$thisWeekScore;
			
			if($week > 9)
				$query = "UPDATE playerlist SET week".$week."=".$thisWeekScore." WHERE playerCode=".$PlayerCode;
			else
				$query = "UPDATE playerlist SET week0".$week."=".$thisWeekScore." WHERE playerCode=".$PlayerCode;
				
			echo "<BR>".$query;
			//$result = mysqli_query($connect, $query);
		}
	}
	else
	{
		echo "<BR>ERROR: opening file ".$file;
	}	
}

function searchFileForString2010($file,$week) 
{
	$section = file_get_contents($file, true);
	if ($section != FALSE)
	{	
		// e,g, 2009
		// <td><a href='/statistics/points/1001'>van der Sar, E</a></td>
		//<td><a href='/statistics/club-by-club/MUN'>Manchester United</a></td>
		//<td>&pound;4m</td>
		//<td>0.0</td>
		//<td>0</td>
		
		//<td class='first'><a href='/statistics/points/1001'>van der Sar, E</a></td>
		//<td class='second'><a href='/statistics/club-by-club/MUN'>Manchester United</a></td>
		//<td class='third'>&pound;4.0 m</td>
		//<td class='fourth'>0.0</td>
		//<td class='fifth last'>0</td>
		
		//$PlayerIdPattern = "/a href='\/statistics\/points\//";
		//$PlayerIdFixedOffset = strlen($PlayerIdPattern) - 5;
		
		// e.g. 2010 <tr id='p1002'><td>Cech, P</td><td>CHE</td><td>4.0</td><td>10.4%</td><td>6</td><td></td></tr>
		$PlayerIdPattern = "/<tr id='p/";
		$PlayerIdFixedOffset = strlen($PlayerIdPattern) - 2;
		
		//$PlayerRowDetect = "/<td/";
		//$PlayerRowDetectOffset = 23;
		$PlayerRowDetect = "/<td class/";
		$PlayerRowDetectOffset = 21;
		
		
		$PlayerLastPointsStartFixedOffset = strlen($PlayerLastPointsStartPattern) - 1;
		
		$offset = 0;
		
		while(preg_match($PlayerIdPattern, $section, $matches, PREG_OFFSET_CAPTURE, $offset))
		{
			$PlayerIdOffset = $matches[0][1] + $PlayerIdFixedOffset;		// Index into $section string to where the player code ID starts
	
			//echo"<BR>Code ".$section[$PlayerIdOffset].$section[$PlayerIdOffset+1].$section[$PlayerIdOffset+2].$section[$PlayerIdOffset+3];
			$PlayerCodeArray = array($section[$PlayerIdOffset],$section[$PlayerIdOffset+1],$section[$PlayerIdOffset+2],$section[$PlayerIdOffset+3]);
			
			$PlayerCode = implode($PlayerCodeArray);
			
			$offset = $PlayerIdOffset;
			
			// Count four lots of <td>
			//echo "<BR>here";
			for ($count = 0; $count <= 4; $count++)
			{
				if (preg_match($PlayerRowDetect, $section, $matches, PREG_OFFSET_CAPTURE, $offset))
				{
					$offset = $matches[0][1]+$PlayerRowDetectOffset;
					if ($count == 4)
					{
						// Get start offset for points
						$totalScoreStartOffset = $matches[0][1]+$PlayerRowDetectOffset;
						
						// get end offset for points
						if (preg_match("/<\/td>/", $section, $matches, PREG_OFFSET_CAPTURE, $offset))
						{
							$totalScoreEndOffset = $matches[0][1];
						}
						//echo "<BR>end ".$totalScoreEndOffset." start ".$totalScoreStartOffset;
						//echo "<BR>$section[$totalScoreStartOffset]"." ".$section[$totalScoreStartOffset+1]." ".$section[$totalScoreStartOffset+2]." ".$section[$totalScoreStartOffset+3]." ".$section[$totalScoreStartOffset+4]." ".$section[$totalScoreStartOffset+5]." ".$section[$totalScoreStartOffset+6]." ".$section[$totalScoreStartOffset+7]." ".$section[$totalScoreStartOffset+8];
						for ($scoreCount = 0; $scoreCount < ($totalScoreEndOffset-$totalScoreStartOffset); $scoreCount++)
						{
							$ScoreArray[$scoreCount] = $section[$totalScoreStartOffset+$scoreCount];
						}
						
						if ($totalScoreEndOffset != $totalScoreStartOffset)
						{
							$totalScore = implode($ScoreArray);
							//echo "<BR>total ".$totalScore;
						}
						else
						{
							$totalScore = 0;
						}
						unset($ScoreArray);
					}
				}
			}
			// Get current total score for this player
			$cDatabase = new database();

			$connect = $cDatabase->connectToDatabase();
			$activeDatabase = $cDatabase->getActiveDatabase($connect);
			$db = $cDatabase->selectDatabase($connect, $activeDatabase);
			
			$maxWeeks = $cDatabase->GetMaxWeeks($connect);
			
			$selectArray[0] = '*';
			$result = $cDatabase->selectFromDatabase($connect, 'playerlist', $selectArray, 'playerCode', $PlayerCode, NULL, NULL);
			
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			//echo "<BR>result $result ".$row['playerName'];
			if ($row['playerName'] == NULL)
			{
				// This player is not in the database
				echo "<BR>Player not in database ".$PlayerCode;
			}
			
			$currentPlayerScore = getPlayerScore($row, $maxWeeks);
			
			$thisWeekScore = $totalScore - $currentPlayerScore;
			//echo "<BR>Total ".$totalScore." Current ".$currentPlayerScore;
			//echo "<BR>PlayerScore = ".$thisWeekScore;
			
			if($week > 9)
				$query = "UPDATE playerlist SET week".$week."=".$thisWeekScore." WHERE playerCode=".$PlayerCode;
			else
				$query = "UPDATE playerlist SET week0".$week."=".$thisWeekScore." WHERE playerCode=".$PlayerCode;
				
			echo "<BR>".$query;
			$result = mysqli_query($connect, $query);
		}
	}
	else
	{
		echo "<BR>ERROR: opening file ".$file;
	}	
}

function getPlayerScore($row, $maxWeeks)
{
	$playerScore = 0;
			
	for ($j = 1; $j <= $maxWeeks; $j++)
	{
		$week = getWeekVariable($j);
		//echo "<BR>week ".$week." row ".$row[$week];
		$playerScore += $row[$week];
	}
	
	return $playerScore;
}

function addPlayerScoresMenu($playerCode, $playerName, $numberPlayers, $week, $weekScore, $updateFlag)
{
	$playerScoreArray = $_POST['playerScoreArray'];
	$playerCodeArray = $_POST['playerCodeArray'];
	
	if ($updateFlag == 1)
		$buttonLabel = "Update Scores";
	else
		$buttonLabel = "Add Scores";
		
	echo "\n<form action=";
	echo "DB_ProcessScores.php?numberPlayers=".$numberPlayers."&week=".$week;
	echo " method='POST'>";
  	//echo "<table border='0'>";
	//for ($i = 0; $i < $numberPlayers; $i++)
	//{ 
	//	echo "<tr><td>";
	//	echo "<INPUT TYPE='text' readonly='true' NAME='playerCodeArray[]' VALUE='$playerCode[$i]' size='4' maxlength='4'>";
	//	echo "</td><td>".$playerName[$i]."</td>";
	//	echo "<td><INPUT TYPE='text' NAME='playerScoreArray[]' VALUE='$weekScore[$i]' size='3' maxlength='3'>";
	//	echo "</td></tr>";
	//}
	//echo "</table><div align='center'><table>";
	echo "\n<td colspan='2' align='center'>";
	echo "<input name='addScoresButton' type='submit' id='addScores' value='".$buttonLabel."'></td>";
	echo "\n</form>";
}

echo $cPage->getContentStringEnd();
echo $cPage->getMenu();
echo $cPage->getClear();
echo $cPage->pageStringEnd();
echo $cPage->getFooter();
?>
